package com.aeks.servlet;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.aeks.divide.FileDivide;
import com.aeks.user.AboutUser;

import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

public class FileDealServlet extends HttpServlet {
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();

		boolean isSuccess = true;

		DiskFileItemFactory disk = new DiskFileItemFactory();
		disk.setSizeThreshold(1024 * 5);// 设置上传缓冲区容量为5k
		String servletPath = this.getServletContext().getRealPath("/");// 获得服务器所在地址

		String path = servletPath + "tempFile";
		File file = new File(path);
		if (!file.exists()) {
			file.mkdirs();
		}
		
		String filePath = "";
		String fileName = "";
		String saveName = "";//保存在服务器上的文件名，由日期+随机数 组成
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		saveName += sdf.format(new java.util.Date());
		
		for(int i=0; i<6; i++) {//得到6位10以内的随机数
			Random random = new Random();
			int r = random.nextInt(10);
			saveName += r;
		}

		disk.setRepository(file);
		long maxsize = 1024 * 1024 * 5;
		ServletFileUpload sfu = new ServletFileUpload(disk);
		sfu.setSizeMax(maxsize);// 限制最大上传容量为5M

		List<FileItem> list = null;
		try {
			list = sfu.parseRequest(request);
		} catch (FileUploadException e) {
			isSuccess = false;
		}

		Iterator it = null;
		try {
			it = list.iterator();
		} catch (NullPointerException e) {
			out.println("<script language='javascript'>");
			out.println("alert('不支持你所上传文件的类型')");
			out.println("</script>");
			isSuccess = false;
		}

		if (it != null) {
			while (it.hasNext()) {
				FileItem fileItem = (FileItem) it.next();
				if (!fileItem.isFormField()) { // 为文件上传域
					filePath = fileItem.getName();
					int index = filePath.lastIndexOf("\\");
					fileName = filePath.substring(index + 1);//文件的实际文件名
					filePath = path + "\\" + saveName + fileName;
					//System.out.println(filePath);
					File f = new File(filePath);
					
					InputStream is = fileItem.getInputStream();
					try {
						fileItem.write(f);
					} catch (Exception e) {
						e.printStackTrace();
						isSuccess = false;
						break;
					}
					
					String size = (new Long(fileItem.getSize())).toString();
					//System.out.println(size);
					
					
					byte[] b = new byte[1024];
					int i = is.read(b);
					boolean getTitle = false;
					boolean getBrief = false;
					boolean getKey = false;
					boolean getText = false;
					while (i != -1) {
						String s = new String(b, 0, i);
						//System.out.println("before:\n" + s);

						s.replaceAll("[a-zA-z]", "");// 去掉英文
						//System.out.println("after:\n" + s);
						if (!getTitle) {// 还没获得标题
							int bi = s.indexOf("摘要");
							int ki = s.indexOf("关键词");
							//System.out.println(bi + ":" + ki);
							if (bi != -1 && ki != -1) {// 得到”摘要“和”关键字“字样
								int dividePart = FileDivide.getTitleBriefkey(s,
										path, bi, ki, saveName);
								if (dividePart == 1) {// ?根据返回值判断是否开始获得正文
									getTitle = true;
									getBrief = true;
									getKey = true;
								} else if (dividePart == 2) {
									getTitle = true;
									getBrief = true;
									getKey = true;
									getText = true;
								} else {
									isSuccess = false;
									break;
								}
							} else if (bi != -1 && ki == -1) {// 只得到“摘要”字样
								boolean isDivideOk = FileDivide.getTitleBrief(
										s, path, bi, saveName);
								if (isDivideOk) {
									getTitle = true;
									getBrief = true;
								} else {
									isSuccess = false;
									break;
								}
							} else {
								isSuccess = false;
								out.println("<script language='javascript'>");
								out.println("alert('不能获取文献标题！');");
								out.println("window.location.href='main.jsp'");
								out.println("</script>");
								break;
							}
						} else if (getTitle && getBrief && !getKey) {// 还没得到关键字
							int ki = s.indexOf("关键字");
							if (ki != -1) {// 得到”关键字“字样
								int dividePart = FileDivide.getBriefKey(s,
										path, ki, saveName);
								if (dividePart == 1) {
									getKey = true;
								} else if (dividePart == 2) {
									getKey = true;
									getText = true;
								} else {
									isSuccess = false;
									break;
								}
							} else if (ki == -1) {// 全为摘要
								boolean isDivideOk = FileDivide.getBrief(s,
										path, saveName);
								if (!isDivideOk) {
									isSuccess = false;
									break;
								}
							} else {
								isSuccess = false;
								out.println("<script language='javascript'>");
								out.println("alert('不能获取文献关键字！');");
								out.println("window.location.href='main.jsp'");
								out.println("</script>");
								break;
							}
						} else if ((getTitle && getBrief && getKey && !getText)
								|| (getTitle && getBrief && getKey && getText)) {// 获取正文
							boolean isDivideOk = FileDivide.getText(s,
									path, saveName);
							if (!isDivideOk) {
								isSuccess = false;
								break;
							} 
						}
						
						i = is.read(b);
					}//while
				}//if 
				
			}// while
		}// if
		//System.out.println(isSuccess);
		boolean result = false;
		int n = -1;
		if(isSuccess) {
			HttpSession session = request.getSession();
			String userName = (String)session.getAttribute("username");
			n = AboutUser.setRandName(saveName, fileName, userName);
			if(n == 0) {
				result = false;
			} else {
				//System.out.println("fileID....:" + n);
				session.setAttribute("fileID", n);
				result = true;
			}
		}
		
		if(result) {
			out.println("<script language='javascript'>");
			out.println("window.location.href='GetKeyServlet?action=sedivide&savename=" + saveName + "&fileid=" + n + "'");
			out.println("</script>");
		} else {
			out.println("<script language='javascript'>");
			out.println("alert('不能获取正确处理该文献！');");
			out.println("window.location.href='main.jsp'");
			out.println("</script>");
		}
		out.flush();
		out.close();
	}// 方法结束
}
